package com.springmvc.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadServlet extends HttpServlet {

	/** 
	 * @Fields serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		// 实现防盗链功能
		// 获得 referer 头 用于说明来访者来自哪里
		String referer = request.getHeader("referer");
		if (referer == null || !referer.startsWith("http://localhost")) {
			// 是盗链者
			response.sendRedirect("/day06/index.jsp");
			return;
		}

		// 解决response中文乱码问题
		response.setContentType("text/html;charset=utf-8"); // 设置消息体的编码

		// 通过 http 协议 发送的http响应消息头 不能出现中文 中文必须要经过url编码
		String filename = URLEncoder.encode("美女.jpg", "utf-8");

		// 通知浏览器以下载的方式读取资源
		response.setHeader("content-disposition", "attachment;filename=" + filename);

		// 读取图片数据 发给ie浏览器
		String webPath = "/download/美女.jpg"; // 相当于当前web应用的path

		ServletContext servletContext = super.getServletContext();

		InputStream in = servletContext.getResourceAsStream(webPath);

		OutputStream out = response.getOutputStream();

		int len;
		byte[] buffer = new byte[1024];
		while ((len = in.read(buffer)) != -1) {
			out.write(buffer, 0, len);
		}

	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}